package org.jmetrix.bus.impl;

import org.jmetrix.bus.Bus;
import org.jmetrix.bus.Listener;
import org.jmetrix.logging.Logger;
import org.jmetrix.logging.LoggerFactory;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 01.10.11
 */
public class BusImpl implements Bus {
    protected static int DEFAULT_MAX_EVENT_QUEUE_SIZE = 1048576;
    protected static String onEvent = "onEvent";
    private final Map<Class, Collection<Listener>> eventListeners = new LinkedHashMap<Class, Collection<Listener>>();
    private Publisher publisher = new Publisher();
    private Thread publishingThread;
    protected Queue eventQueue = new LinkedBlockingQueue(DEFAULT_MAX_EVENT_QUEUE_SIZE);
    volatile boolean shutdown = false;
    private Logger logger = LoggerFactory.getLogger(BusImpl.class);


    public BusImpl() {
    }

    protected Logger getLogger() {
        return logger;
    }

    private synchronized void createAndStartPublisherThreadIfNeeded() {
        if (publishingThread == null && !eventQueue.isEmpty() && !eventListeners.isEmpty()) {
            publishingThread = new Thread(publisher, BusImpl.class.getName() + "-PublishingThread");
            publishingThread.setDaemon(true);
            publishingThread.start();
        }
    }

    @Override
    public void publish(final Object object) {
        if (shutdown) {
            getLogger().warn("Bus is unavailable because of shutdown called");
        }

        if (eventQueue.offer(object)) {
            if (publishingThread == null) { // Fast check
                createAndStartPublisherThreadIfNeeded();
            }
            publisher.wakeUp();
        } else {
            getLogger().warn("Can not publish event {} in the bus: internal queue is full", object);
        }
    }

    private void doPublish(Object object) {
        final Set<Map.Entry<Class, Collection<Listener>>> entriesCopy;
        synchronized (eventListeners) {
            entriesCopy = new LinkedHashSet<Map.Entry<Class, Collection<Listener>>>(eventListeners.entrySet());
        }
        for (final Map.Entry<Class, Collection<Listener>> eventClassListeners : entriesCopy) {
            if (eventClassListeners.getKey().isAssignableFrom(object.getClass())) {
                final Collection<Listener> listeners = eventClassListeners.getValue();
                for (final Listener listener : listeners) {
                    listener.onEvent(object);
                }
            }
        }
    }

    @Override
    public void addListener(final Listener listener) {
        final Class eventClass = getEventClass(listener);
        synchronized (eventListeners) {
            Collection<Listener> listeners = eventListeners.get(eventClass);
            if (listeners == null) {
                listeners = new LinkedList<Listener>();
                eventListeners.put(eventClass, listeners);
            }
            listeners.add(listener);
        }
        createAndStartPublisherThreadIfNeeded();
    }

    @Override
    public void shutdown() {
        shutdown = true;
        publisher.wakeUp();
        eventQueue.clear();
    }

    protected static Class getEventClass(final Listener listener) {
        final Method[] methods = listener.getClass().getMethods();
        Method onEventMethod = null;
        for (final Method method : methods) {
            if (method.getName().equals(onEvent) &&
                    method.getParameterTypes().length == 1) {
                onEventMethod = method;
                break;
            }
        }
        if (onEventMethod == null) {
            throw new IllegalStateException("Cannot evaluate event type to handle - " + onEvent + " method was not detected");
        }
        return onEventMethod.getParameterTypes()[0];
    }

    private class Publisher implements Runnable {
        final Object wakeupSignal = new Object();

        public void wakeUp() {
            synchronized (wakeupSignal) {
                wakeupSignal.notifyAll();
            }
        }

        @Override
        public void run() {
            while (!shutdown) {
                Object event = eventQueue.poll();
                while (!shutdown && event != null) {
                    doPublish(event);
                    event = eventQueue.poll();
                }
                if (!shutdown) {
                    waitForSignal();
                }
            }
        }

        private void waitForSignal() {
            try {
                synchronized (wakeupSignal) {
                    wakeupSignal.wait();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
